package com.ruoyi.web.util;

import com.ruoyi.web.controller.sso.domain.GatewayBean;
import sviolet.smcrypto.SmCryptoUtil;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * description:
 * auth fcb
 * date 2025-04-14 09:02
 **/
public class CreateSignUtil {



    public static String createSign(GatewayBean gatewayBean) {
        // 获取sign
        String content = getSignCheckContentV2(gatewayBean);
        return SmCryptoUtil.sm3Encode(content.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 获取签名认证的参数内容
     *
     * @param gatewayBean
     * @return
     */
    public static String getSignCheckContentV2(GatewayBean gatewayBean) {
        if (gatewayBean == null) {
            return null;
        } else {
            Map<String, String> newParams = new HashMap<String, String>(16);
            newParams.put("app_id", gatewayBean.getAppUniqueId());
            newParams.put("interface_id", gatewayBean.getInterfaceUniqueId());
            newParams.put("version", gatewayBean.getVersion());
            String bizContent = gatewayBean.getBizContent().replace("&quot;", "\"");
            newParams.put("biz_content", bizContent);
            newParams.put("charset", gatewayBean.getCharset());
            newParams.put("timestamp", gatewayBean.getTimestamp());
            newParams.put("origin", gatewayBean.getOrigin());
            return getSignContent(newParams);
        }
    }

    /**
     * 获取参数内容
     *
     * @param sortedParams
     * @return
     */
    public static String getSignContent(Map<String, String> sortedParams) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;

        for (int i = 0; i < keys.size(); ++i) {
            String key = (String) keys.get(i);
            String value = (String) sortedParams.get(key);
            if (areNotEmpty(new String[]{key, value})) {
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                ++index;
            }
        }

        return content.toString();
    }


    public static boolean areNotEmpty(String[] values) {
        boolean result = true;
        if ((values == null) || (values.length == 0)) {
            result = false;
        } else {
            for (String value : values) {
                result &= !(isEmpty(value));
            }
        }
        return result;
    }

    public static boolean isEmpty(String value) {
        int strLen;
        if ((value == null) || ((strLen = value.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < strLen; ++i) {
            if (!(Character.isWhitespace(value.charAt(i)))) {
                return false;
            }
        }
        return true;
    }
}
